<template>
    <div class="inputContent">
        <el-input
            :id="`inputContent-${props.reKey}`"
            v-model="inputValue"
            class="input-content-textarea"
            type="textarea"
            :disabled="props.disabled || props.inputDisabled"
            :rows="props.rows"
            :maxlength="props.maxLength"
            :placeholder="props.placeholder"
            show-word-limit
            @input="changeWords" />
        <div class="input-content-config">
            <div class="config-left">
                <div v-for="item in tabs" :key="item?.name" class="input-content-item">
                    <component
                        :is="item.comName"
                        v-if="item?.comName"
                        :disabled="props.disabled"
                        @change="selectEmoji" />
                    <span
                        v-else
                        class="item-text"
                        :class="{ insert: ![1, 2].includes(item.name), disabled: props.disabled }"
                        @click="tabHandleClick(item)">
                        {{ item?.label }}
                    </span>
                </div>
            </div>
            <div class="config-right">
                <el-button v-for="item in btns" :key="item.value" size="small" @click="btnHandle(item)">
                    {{ item.label }}
                </el-button>
            </div>
        </div>
    </div>

    <ZWMatericalLib ref="ZWMatericalLibRef" @submit="getMaterlib" />
</template>

<script setup lang="ts">
import {
    reactive,
    ref,
    computed,
    watch,
    onMounted,
    nextTick,
    withDefaults,
    defineProps,
    shallowRef,
    onUnmounted
} from 'vue';
import ZWMatericalLib from '@/components/channelNew/ZWMatericalLib.vue';
import Emoji from './Emoji.vue';
import bus from '@/utils/bus';

const ZWMatericalLibRef = ref<HTMLElement | null>();

interface Props {
    modelValue: string;
    disabled: boolean;
    inputDisabled: boolean;
    singleList: Array<number>;
    content: string;
    reKey: string;
    placeholder: string;
    maxLength: number;
    rows: number;
    tabs: Array<number>;
    btns: Array<number>;
}
interface TabsType {
    name: number;
    [propsName: string]: string | number;
    comName?: InstanceType<typeof Emoji> | null;
}

interface FnType {
    (): void;
}
interface BtnsType {
    [propsName: string]: string | number;
    value: number;
}

const props = withDefaults(defineProps<Props>(), {
    modelValue: '',
    disabled: false,
    inputDisabled: false,
    singleList: () => [],
    content: '',
    reKey: '',
    placeholder: '请输入消息',
    maxLength: 1000,
    rows: 6,
    tabs: () => [1, 2],
    btns: () => []
});

const inputValue = ref<string>('');
const text_ids = reactive<Array<number>>([]);
const tabsList = reactive<Array<TabsType>>([
    {
        label: '选择文本',
        value: '',
        name: 1
    },
    {
        label: '😊',
        value: '',
        name: 2,
        comName: shallowRef(Emoji)
    },
    {
        label: '#员工别名#',
        value: '##员工别名##',
        name: 3
    },
    {
        label: '#客户姓名#',
        value: '##客户姓名##',
        name: 4
    },
    {
        label: '#员工姓名#',
        value: '##员工姓名##',
        name: 5
    },
    {
        label: '#客户昵称#',
        value: '##客户昵称##',
        name: 6
    },
    {
        label: '#客户名称#',
        value: '##客户名称##',
        name: 7
    },
    {
        label: '#打卡口令#',
        value: '##打卡口令##',
        name: 8
    },
    {
        label: '#打卡查询短链#',
        value: '##打卡查询短链##',
        name: 9
    }
]);

const btnList = reactive<Array<BtnsType>>([
    {
        label: '清空文本',
        value: 1
    }
]);

// eslint-disable-next-line vue/no-dupe-keys
const tabs = computed(() => {
    if (props.tabs.length) {
        return tabsList.filter(item => {
            if (props.tabs.includes(item.name)) {
                return item;
            }
        });
    } else {
        return tabsList.slice(0, 2);
    }
});

// eslint-disable-next-line vue/no-dupe-keys
const btns = computed(() => {
    if (props.btns.length) {
        return btnList.filter(item => {
            if (props.btns.includes(item.value)) {
                return item;
            }
        });
    } else {
        return [];
    }
});

const emit = defineEmits(['update:modelValue', 'change']);

const changeWords = () => {
    const params = {
        content: inputValue.value,
        text_ids: text_ids,
        reKey: props.reKey
    };
    bus.emit('changeContent', params);
    emit('update:modelValue', inputValue.value);
};

const tabHandleClick = (tab: any) => {
    if (!props.disabled) {
        const { name } = tab;

        if (name) {
            switch (Number(name)) {
                case 1:
                    selectText();
                    break;
                default:
                    insertName(tabsList.find((item: any) => item.name === Number(name)).value as string);
                    break;
            }
        }
    }
};

const btnHandle = (item: any) => {
    const { value } = item;
    switch (value) {
        case 1:
            clear();
            break;
    }
};

const clear = () => {
    inputValue.value = '';
    changeWords();
};

const selectText = () => {
    ZWMatericalLibRef.value.showTabs = ['1'];
    ZWMatericalLibRef.value.baseId = '1';
    ZWMatericalLibRef.value.multiple = !props.singleList.includes(0);
    ZWMatericalLibRef.value.selectInfoList.splice(0);
    ZWMatericalLibRef.value.materVisible = true;
};
const selectEmoji = ({ value }: { value: string }): void => {
    insertInputContent(value);
};
const insertName = (name: string) => {
    insertInputContent(name);
};
const getMaterlib = (res: any[]): void => {
    const { data, type } = res[0];
    if (type === 0) {
        const str = data.reduce((pre: string, next: any): string => {
            return pre + next.content;
        }, '');
        const arr = data.map((item: any) => item.id);
        text_ids.push(...arr);
        insertInputContent(str);
    }
};

const insertInputContent = (content: any) => {
    const arr = Array.from(inputValue.value);
    if (arr.length >= props.maxLength) {
        return;
    }
    const el = document.getElementById(`inputContent-${props.reKey}`) as HTMLInputElement;
    const inpIndex = el.selectionStart as number;
    const textareaContent = inputValue.value;
    const start = `${textareaContent.substring(0, inpIndex)}${content}`;
    const end = textareaContent.substring(inpIndex, textareaContent.length);
    if (props.singleList.includes(0)) {
        inputValue.value = content as string;
    } else {
        inputValue.value = `${start}${end}`;
    }
    inputValue.value = `${start}${end}`.slice(0, props.maxLength);
    // inputValue.value = Array.from(inputValue.value).splice(0, props.maxLength).join('');
    changeWords();
    nextTick(() => {
        el.selectionStart = start.length;
        el.selectionEnd = start.length;
        el.focus();
    });
};

const init = (val: string) => {
    inputValue.value = val;
    nextTick(() => {
        changeWords();
    });
};

const clearInput = () => {
    init('');
};

watch(
    () => props.content,
    val => {
        init(val);
    },
    { immediate: true, deep: true }
);

onMounted(() => {
    bus.on('changeContentAlready', init);
});

onUnmounted(() => {
    bus.off('changeContentAlready', init);
});

defineExpose({
    inputValue,
    insertInputContent,
    clearInput
});
</script>

<style lang="scss" scoped>
$color: #e9e9e9;
$border: 1px solid $color;

.inputContent {
    border: 1px solid #e9e9e9;
    padding: 6px;
    padding-bottom: 0;
    border-radius: 4px;

    .input-content-textarea {
        :deep(.el-textarea__inner) {
            box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
            resize: none;
            cursor: default;
            padding: 2px;
            background-color: transparent;
            border: none;
        }
    }

    .input-content-config {
        height: 40px;
        border-top: $border;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .config-left {
            display: flex;
            align-items: center;

            .input-content-item {
                margin-right: 10px;
                display: flex;
                align-items: center;
                height: 16px;
                border-right: 1px solid #e9e9e9;
                padding: 0 8px;

                &:last-of-type {
                    border: none;
                }

                &:hover {
                    cursor: pointer;
                }

                .item-text {
                    font-size: 12px;
                    line-height: 1;
                    color: #555;
                    white-space: nowrap;

                    &:hover {
                        color: #f96b02;
                    }
                }

                // .insert{
                //   color: #F96B02;
                //   &:hover{
                //     color: #F98B33;
                //   }
                // }
                .disabled {
                    color: #888;

                    &:hover {
                        cursor: not-allowed;
                        color: #888;
                    }
                }
            }
        }

        .config-right {
            margin-left: 16px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
    }
}
</style>
